<template>
	<div>
		<div class="wrapper" :style="{width:originalData.img_width+'px',height:originalData.img_height+'px'}">
			<div class="wrapper-content" :class="{wrapper_trans:isTrans}" :style="{width:originalData.img_width*(num+2)+'px',height:originalData.img_height+'px',left:-originalData.img_width+'px'}" ref="wrapperContent">
				<img class="wrapper-content_img" v-if="swipimgage[swipimgage.length-1]" @click="jumpEvent(swipimgage[swipimgage.length-1])" :src="swipimgage[swipimgage.length-1].publicityPicture ||'static/image/demo2.png'" :style="{width:originalData.img_width+'px',height:originalData.img_height+'px'}" />
				<img class="wrapper-content_img" v-if="item" v-for="(item,index) in swipimgage" @click="jumpEvent(item)" :src="item.publicityPicture || 'static/image/demo2.png'" :style="{width:originalData.img_width+'px',height:originalData.img_height+'px'}" :key="index" />
				<img class="wrapper-content_img" v-if="swipimgage[0]" @click="jumpEvent(swipimgage[0])" :src="swipimgage[0].publicityPicture||'static/image/demo2.png'" :style="{width:originalData.img_width+'px',height:originalData.img_height+'px'}" />
			</div>
			<div class="wrapper-buttons" :style="{left:(originalData.img_width-12*num)/2+'px'}">
				<span v-for="(tab,index) in swipimgage" :class="['wrapper-button',{'wrapper_on':index==flag}]" @click="turnTo(index)" :key="index"></span>
			</div>
		</div>
	</div>
</template>

<script>
	import { mapGetters,mapMutations } from "vuex";
	import { NAVIGATE } from "../../../config/postMessage-types";
	import handlePath from "../../../utils/lxn/handlePath"
	export default {
		props: {
			swipimgage: {
				type: Array,
				default: () => []
			},
			swipimgagewidth: "",
			swipimgageheight: ""
		},
		data() {
			return {
				originalData: {
					img_width: this.swipimgagewidth,
					img_height: this.swipimgageheight,
					num: this.swipimgage.length,
					delay: 300,
				},
				isTrans: true, //因为到最后一张图片，index为1时，需要立即跳到第二张index也为1的图片，这个用来是否给出transition
				timer: null, //setInterval
				timer2: null,
				timer3: null,
				clickdelay: false, //用来防止连续点击
				flag: 0,
				startx: '',
				offsetx: 0,
				startTime: '',
			}
		},
		computed: {
			num() {
				return this.swipimgage.length;
			},
			isApp() {
				return window.isApp;
			},
			...mapGetters('wxh', [
                'userInfo'
            ]),
            hasUserInfo() {
                return Object.keys(this.userInfo).length;
            },
		},
		methods: {
			...mapMutations('xxy', [
				"setpopupVisible",
				"setactivePic",
				"setstoptouch"
			]),
			jumpEvent(item) {
				if (!item.extendField) return;
				if (!this.isApp) {
					// var urldata = JSON.parse(item.extendField).url.path
					var urldata = handlePath(item)
					if(urldata) {
						this.$router.push({
							path : urldata
							// name: "MiddleWare",
							// params: {
							// 	pageName: urldata
							// }
						})
					}
				} else if (this.isApp){
					var urldata = JSON.parse(item.extendField).url
					if(urldata.valueArray[0] == '商品详情页面' ) {
						this.gotornpage('Detail', urldata.path.split("=")[1])
					} else if(urldata.valueArray[0] == '分类页面'){
						this.gotornpage('GoodsClassify', urldata.path.split("=")[1])
					}else if(urldata.valueArray[0] == '其他页面') {
						if(urldata.path == 'IntegralBuy') {
							if(this.hasUserInfo ===0) {
								this.gotornpage('Login')
							}else{
								this.gotornpage(urldata.path)
							}
						}else if(urldata.path == 'Coupons'){
							this.gotornpage('CouponsAcquire')
						} else if (urldata.path == 'buyGiftCard') {
							if(this.hasUserInfo ===0) {
								this.gotornpage('Login')
							} else{
								this.gotornpage('BuyGiftCard')
							}
						} else if(urldata.path == 'foodChecked'){
							if(this.hasUserInfo ===0) {
								this.gotornpage('Login')
							}
							else{
								this.gotornpage('FoodCheck')
							}
						} else if(urldata.path == 'prize_card'){
								if(this.hasUserInfo ===0) {
									this.gotornpage('Login')
								} else {
								this.$router.push({
									name: "MiddleWare",
									params: {
										pageName: urldata.path
									}
								})
							}
						} else if(urldata.path == 'integral'){
							console.log("urldata.path",urldata.path)
								if(this.hasUserInfo ===0) {
									this.gotornpage('Login')
								} else {
								this.$router.push({
									name: "MiddleWare",
									params: {
										pageName: urldata.path
									}
								})
							}
						} else if(urldata.path == 'login'){
							this.gotornpage('Login')
						} else if(urldata.path == 'register'){
							this.gotornpage('Regrester')
						} else {
							this.$router.push({
								name: "MiddleWare",
								params: {
									pageName: urldata.path
								}
							})
						}
					}
				}
			},
			gotornpage(page, code) {
				let params = {}
				if(page=='Detail'){
					params = {
						screen: page,
						params:{
							goodsCode: code
						}
					}
				}else if(page=='GoodsClassify'){
					params = {
						screen: page,
						params:{
							classCode: code
						}
					}
				} else {
					params = {
						screen: page,
					}
				}
				let goBackIns = {
					type: NAVIGATE,
					params: params
				}
				window.postMessage(JSON.stringify(goBackIns));
			},
			go(inx) {
				var node = this.$refs.wrapperContent;
				var self = this;
				this.isTrans = true;
				node.style.left = -this.originalData.img_width * (this.flag + 1 + inx) + 'px';
				this.timer3 = setTimeout(function() {
					if(self.flag + inx == self.num) {
						self.flag = 0;
						self.isTrans = false;
						node.style.left = -self.originalData.img_width * (self.flag + 1) + 'px';
					} else if(self.flag + 1 + inx == 0) {
						self.flag = self.num - 1;
						self.isTrans = false;
						node.style.left = -self.originalData.img_width * (self.flag + 1) + 'px';
					} else {
						self.flag = self.flag + inx;
					}
				}, this.originalData.delay)

			},
			next() {
				if(this.clickdelay) {
					return
				}
				this.clickdelay = true
				if(this.flag == this.num - 1) {
					this.flag = 0
				} else {
					this.flag += 1
				}
				this.animate(this.originalData.img_width)

			},
			prev() {
				if(this.clickdelay) {
					return
				}
				this.clickdelay = true
				if(this.flag == 0) {
					this.flag = this.num - 1
				} else {
					this.flag -= 1
				}
				this.animate(-this.originalData.img_width)
			},
			animate(offset) {
				var node = this.$refs.wrapperContent
				var self = this;
				if(node) {
					var left = parseInt(node.style.left) - offset
					this.isTrans = true
					node.style.left = left + 'px'
					this.timer2 = setTimeout(function() {
						if(left < -(self.num * self.originalData.img_width)) {
							self.isTrans = false
							node.style.left = -self.originalData.img_width + 'px'
							self.clickdelay = false //当到达最后一张图片时
						}
						if(left > -100) {
							self.isTrans = false
							node.style.left = -self.num * self.originalData.img_width + 'px'
							self.clickdelay = false //当到达第一张图片时
						}
					}, this.originalData.delay)
				}
			},
			play() {
				if(this.timer) {
					clearInterval(this.timer)
				}
				var self = this;
				this.timer = setInterval(function() {
					self.next()
				}, 3500)
			},
			stop() {
				this.clickdelay = false //用来防止连续点击
				clearInterval(this.timer)
				this.timer = null
			},
			turnTo(index) {
				this.stop()
				clearInterval(this.timer2)
				this.timer2 = null
				clearInterval(this.timer3)
				this.timer3 = null
				if(index == this.flag) {
					return
				} else {
					var offset = (index - this.flag) * this.originalData.img_width
					this.flag = index
					this.animate(offset)
				}
				this.play();
			},

			/*----------------------------------*/
			touch() {
				var self = this;
				var startHandler = function(evt) {
					self.setstoptouch(false)
					self.stop()
					self.startx = evt.touches[0].pageX;
					self.offsetx = 0;
					self.startTime = new Date * 1;
				};
				var moveHandler = function(evt) {
					evt.preventDefault();
					self.offsetx = evt.touches[0].pageX - self.startx;
					node.style.left = -self.originalData.img_width * (self.flag + 1) + self.offsetx + 'px'
				};
				var endHandler = function(evt) {
					clearInterval(self.timer2)
					self.timer2 = null
					var boundary = self.originalData.img_width / 6;
					var endTime = new Date() * 1;
					if(endTime - self.startTime > 800) {
						if(self.offsetx >= boundary) {
							self.go(-1)
							//进入前一张
						} else if(self.offsetx < -boundary) {
							self.go(1)
							//进入后一张
						} else {
							self.go(0)
							//留在本页
						}
					} else {
						if(self.offsetx > 50) {
							self.go(-1)
							//进入前一张
						} else if(self.offsetx < -50) {
							self.go(1)
							//进入后一张
						} else {
							self.go(0)
							//留在本页
						}
					};
					self.play();
				};
				var node = this.$refs.wrapperContent;
				/*node.removeEventListener("touchstart", startHandler);
				  node.removeEventListener("touchmove", moveHandler);
				  node.removeEventListener("touchend", endHandler);*/
				node.addEventListener("touchstart", startHandler);
				node.addEventListener("touchmove", moveHandler);
				node.addEventListener("touchend", endHandler);
			}
		},
		mounted() {
			/*下面是判断过渡动画是否完成*/
			var node = this.$refs.wrapperContent
			var transitions = {
				'transition': 'transitionend',
				'OTransition': 'oTransitionEnd',
				'MozTransition': 'transitionend',
				'WebkitTransition': 'webkitTransitionEnd'
			}
			var self = this

			for(var t in transitions) {

				if(node.style[t] !== undefined) {
					var transitionEvent = transitions[t];
				}
			}
			transitionEvent && node.addEventListener(transitionEvent, function() {
				self.clickdelay = false
			});
			this.play();
			this.touch();
		},
		watch: {
			swipimgage() {
				this.stop();
				this.play();
				/*this.touch();*/
			}
		},
		created() {},

	}
</script>

<style scoped>
	.wrapper {
		position: relative;
		overflow: hidden;
		/* min-height: 260px; */
	}
	
	.wrapper-content {
		position: absolute;
		left: 0;
		/*z-index: 1;*/
	}
	
	.wrapper-content_img {
		border: none;
		outline: none;
		float: left
	}
	
	.wrapper-buttons {
		position: absolute;
		/*width: 48px;*/
		height: 6px;
		text-align: center;
		bottom: 20px;
		z-index: 2;
	}
	
	.wrapper-button {
		float: left;
		width: 6px;
		height: 6px;
		border-radius: 6px;
		background: gray;
		margin: 0 3px;
		cursor: pointer;
	}
	
	.wrapper-arrow {
		position: absolute;
		width: 40px;
		height: 40px;
		cursor: pointer;
		background-color: RGBA(0, 0, 0, .3);
		color: #fff;
		display: none;
		top: 50%;
		line-height: 40px;
		font-size: 36px;
		text-align: center;
		z-index: 2;
	}
	
	.wrapper:hover .wrapper-arrow {
		display: block;
		background-color: rgba(0, 0, 0, .7);
	}
	
	.wrapper-prev {
		left: 10px;
	}
	
	.wrapper-next {
		right: 10px;
	}
	
	.wrapper_on {
		background-color: yellow
	}
	
	.wrapper_trans {
		transition: left .2s ease
	}
</style>